package com.example.workflow.filter;


import com.example.workflow.exception.ServiceException;
import com.example.workflow.pojo.LoginUser;
import com.example.workflow.util.JwtUtil;
import com.example.workflow.util.RedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
//    private RedisCache redisCache;
    private RedisUtils redisUtils;
    ThreadLocal<Integer> userThreadLocal = new ThreadLocal<>();



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 获取token
        String token = request.getHeader("Authorization");
        String path = request.getRequestURI();
        // 如果路径是 /engine-rest/** 或 /camunda/**，直接放行
        // 明确列出白名单路径，不再使用startsWith
        boolean isWhiteListPath = 
            path.startsWith("/engine-rest") ||
            path.startsWith("/camunda") ||
            path.startsWith("/app/") ||
            path.startsWith("/api/") || 
            path.startsWith("/lib/") ||
            path.equals("/user/login");

        if (!StringUtils.hasLength(token)) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }
        if (isWhiteListPath) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("token非法，重新登录");
        }
        // 从redis中获取用户信息
        String redisKey = "login" + ":" + userId;

        userThreadLocal.set(Integer.parseInt(userId));
        String user = redisUtils.getString(redisKey);



        if (user == null) {
            throw new ServletException("用户登录信息已过期，请重新登录");
        }

        ObjectMapper objectMapper = new ObjectMapper();
        LoginUser loginUser = objectMapper.readValue(user, LoginUser.class);
        log.info("loginUser = {}",loginUser);
        if (Objects.isNull(loginUser)) {
            throw new ServletException("用户未登录");
        }

        // 存入SecurityContextHolder
        // 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);
    }
}

